package com.lagou.edu.service.impl;

import com.lagou.edu.client.EmailClient;
import com.lagou.edu.client.UserClient;
import com.lagou.edu.dao.LagouAuthCodeDao;
import com.lagou.edu.entity.LagouAuthCode;
import com.lagou.edu.service.CodeService;
import com.lagou.edu.util.VerifyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author zhangjinshan
 * @version 1.0
 * @description
 * @date 2021/8/25 下午8:42
 */
@Service
@Slf4j
public class CodeServiceImpl implements CodeService {

    /**
     * 验证码过期时间
     */
    private Long codeExpireTime = 3L;

    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;

    @Autowired(required = false)
    private EmailClient emailClient;

    @Autowired
    private UserClient userClient;


    @Override
    public boolean create(String email) {
        boolean registered = userClient.isRegistered(email);
        if (registered) {
            return false;
        }
        // 保存验证码
        String code = VerifyUtil.createCode();
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setCode(code);
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCreatetime(new Date());
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(codeExpireTime);
        lagouAuthCode.setExpiretime(Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()));
        lagouAuthCodeDao.save(lagouAuthCode);
        // 发送邮件
        return emailClient.sendEmail(email, code);
    }

    @Override
    public Integer validate(String email, String code) {
        LagouAuthCode condition = new LagouAuthCode();
        condition.setCode(code);
        condition.setEmail(email);
        Example<LagouAuthCode> codeExample = Example.of(condition);
        LagouAuthCode lagouAuthCode = lagouAuthCodeDao.findOne(codeExample).get();
        if (ObjectUtils.isEmpty(lagouAuthCode)) {
            return Integer.valueOf(1);
        }
        Date expiretime = lagouAuthCode.getExpiretime();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(expiretime.toInstant(), ZoneId.systemDefault());
        if (localDateTime.isBefore(LocalDateTime.now())) {
            return Integer.valueOf(2);
        }
        return Integer.valueOf(0);
    }
}
